package com.wn.ziroom.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

public class JsonUtils {

    private static final ObjectMapper objMapper = new ObjectMapper();

    public static String toJsonStr(Object obj) {
        try {
            return objMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T toObject(String jsonStr, Class<T> clz) {
        try {
            System.out.println("jsonStr:" + jsonStr);
            return objMapper.readValue(jsonStr, clz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    public static <T> List<T> toList(String jsonStr, Class<T> clz) {
        TypeReference<List<T>> listTypeReference = new TypeReference<List<T>>() {
        };
        // 读取字符串，开始转换
        try {
            return objMapper.readValue(jsonStr, listTypeReference);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
